package com.yaorange.jk.service.impl;

import com.yaorange.jk.dao.BaseDao;
import com.yaorange.jk.entity.Role;
import com.yaorange.jk.entity.User;
import com.yaorange.jk.entity.UserInfo;
import com.yaorange.jk.service.RoleService;
import com.yaorange.jk.service.UserService;
import com.yaorange.jk.utils.Encrypt;
import com.yaorange.jk.utils.MailUtils;
import com.yaorange.jk.utils.Pagination;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * @author coach tam
 * @date 2017/11/1
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    private Logger logger = Logger.getLogger(UserServiceImpl.class);

    @Autowired
    private BaseDao<User,String> userDao;

    @Autowired
    private RoleService roleService;

    @Autowired
    private BaseDao<UserInfo,String> userInfoDao;

    @Autowired
    private SimpleMailMessage message;


    @Autowired
    private JavaMailSender sender;

    @Override
    @Transactional(readOnly = true)
    public Pagination findPage(int pageNo, int pageSize, User user) {
        String hql = "from User u where 1=1";
//        Long degree = user.getUserInfo().getDegree();
//        //3，查询本部门数据
//        if(degree==3)
//        {
//            hql +=" and u.createDept = '"+user.getDept().getId()+"'";
//        }
//        //4,查询本人数据
//        if(degree==4)
//        {
//            hql +=" and u.createBy = '"+user.getId()+"'";
//        }
        return userDao.pageByHql(hql,pageNo,pageSize);
    }


    @Override
    public List<User> findAll() {
        return userDao.getListByHQL("from User");
    }

    @Override
    public void save(User user) {

        //保证邮箱字段不为空
        if(user.getUserInfo()!=null&&user.getUserInfo().getEmail()!=null&&!user.getUserInfo().getEmail().isEmpty())
        {
            user.getUserInfo().setUser(user);
            //初始化密码
            String password = Encrypt.md5(user.getUserName(),user.getUserName());
            user.setPassword(password);

            //设置初始化状态  0:不可用
            user.setState(0l);
            //生成激活码
            String code = UUID.randomUUID().toString();
            user.getUserInfo().setCode(code);
            userDao.save(user);



            //发送激活 邮件
            String subject = "欢迎入职公司";
            String text = "<a href='http://localhost:88/sysadmin/userAction_activity?id="+user.getId()+"&userInfo.code="+code+"'>点击激活你的账号</a>";

            //新开一个子线程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int count = 0;
                    boolean isOk = false;
                    while(count<3&&!isOk)
                    {
                        try
                        {
                            logger.info("正在发送邮件...");
                            MimeMessage message = sender.createMimeMessage();
                            MimeMessageHelper helper = new MimeMessageHelper(message,true);
                            helper.setFrom("yaorange_mail@sina.com");
                            helper.setTo(user.getUserInfo().getEmail());
                            helper.setSubject(subject);
                            helper.setText(text,true);//true,表示发送的是html 正文
                            sender.send(message);
//                            MailUtils.sendMail(user.getUserInfo().getEmail(),subject,text);
                            isOk=true;
                            logger.info("发送邮件成功.");
                        }
                        catch (RuntimeException e)
                        {
                            //隔5秒再发一次
                            try {
                                Thread.sleep(5000);
                                logger.error("发送邮件失败,正在尝试第["+(count+1)+"]次重新发送...");
//                                System.out.println("发送邮件失败,正在尝试第["+(count+1)+"]次重新发送...");
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }
                            count++;
                        } catch (MessagingException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();




        }


    }

    @Override
    public User findById(String id) {
        return userDao.get(User.class,id);
    }

    @Override
    public void update(User model) {
        //根据主键查询出老数据
        User oldUser = userDao.get(User.class,model.getId());
        oldUser.setUserName(model.getUserName());
        oldUser.setDept(model.getDept());
        oldUser.setState(model.getState());
        userDao.update(oldUser);
    }

    @Override
    public void deleteByIds(String[] ids) {
        for (String id :ids)
        {
            userDao.deleteById(User.class,id);
        }
    }

    @Override
    public void updateRole(String id, String[] roleIds) {
        User user = userDao.get(User.class,id);
        //将String[] roleIds -->Set<Role>
        Set<Role> roleSet = new HashSet<>(roleIds.length);
        for (String roleId: roleIds) {
            Role role = roleService.findById(roleId);
            roleSet.add(role);
        }
        user.setRoleSet(roleSet);

        userDao.update(user);
    }

    @Override
    @Transactional(readOnly = true)
    public User findByUsername(String username) {
        return userDao.getByHQL("from User where userName=?",username);
    }

    @Override
    public User activity(User model) {
        model = userDao.getByHQL("from User u where u.id=? and u.userInfo.code=?",model.getId(),model.getUserInfo().getCode());
        if(model!=null)
        {
            model.setState(1l);
            model.getUserInfo().setCode(null);
            userDao.update(model);
        }

        return model;
    }
}
